<template>
    <div>
        <n-card :bordered="false">
            <h2>{{ isEdit ? '编辑仿真' : '添加仿真' }}</h2>
            <n-form :model="agvForm" :rules="formRules" ref="formRef" label-placement="left" label-width="120px"
                :style="{ maxWidth: '300px' }">
                <n-form-item label="AGV编号" path="car_index">
                    <n-input-number v-model:value="agvForm.car_index" />
                </n-form-item>
                <n-form-item label="起始站点ID" path="node_start_id">
                    <n-select v-model:value="agvForm.node_start_id" :options="NodeOptions" />
                </n-form-item>
                <n-form-item label="目标站点ID" path="node_to_id">
                    <n-select v-model:value="agvForm.node_to_id" :options="NodeOptions" />
                </n-form-item>
                <n-form-item label="虚拟设备" path="simulation">
                    <n-radio-group v-model:value="agvForm.simulation">
                        <n-radio v-for="issimulation in simulationOptions" :key="issimulation.value"
                            :value="issimulation.value">{{
                                issimulation.label }}</n-radio>
                    </n-radio-group>
                </n-form-item>
                <n-form-item label="是否连接" path="is_connected">
                    <n-radio-group v-model:value="agvForm.is_connected">
                        <n-radio v-for="isconnected in isConnectedOptions" :key="isconnected.value"
                            :value="isconnected.value">{{
                                isconnected.label }}</n-radio>
                    </n-radio-group>
                </n-form-item>
                <n-form-item label="状态" path="status">
                    <n-select v-model:value="agvForm.status" :options="statusOptions" />
                </n-form-item>
                <n-form-item label="电池电量" path="battery">
                    <n-input-number v-model:value="agvForm.battery" />
                </n-form-item>
                <n-form-item label="角度" path="angle">
                    <n-input-number v-model:value="agvForm.angle" />
                </n-form-item>
                <n-form-item label="速度" path="speed">
                    <n-input-number v-model:value="agvForm.speed" />
                </n-form-item>

                <!-- 操作按钮 -->
                <div class="form-actions">
                    <n-button @click="handleCancel">取消</n-button>
                    <n-button type="primary" @click="submitForm">提交</n-button>
                </div>
            </n-form>

        </n-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { NCard, NForm, NFormItem, NInput, NSelect, NInputNumber, NButton, useMessage, NRadioGroup, NRadio } from "naive-ui";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { API_URLS } from '../../utils/apiConfig';

const router = useRouter();
const route = useRoute();
const message = useMessage();

const loading = ref(false);
const isEdit = ref(false);
const agvId = ref(null);

const formRef = ref(null);
const agvForm = ref({
    car_index: 0,
    x: 0,
    y: 0,
    node_start_id: null,
    node_to_id: null,
    simulation: 1,
    is_connected: 1,
    status: null,
    battery: 95,
    angle: 0,
    speed: 10,
});

const formRules = {
    car_index: { required: true, type: "number", min: 1, max: 100, message: "请输入AGV编号", trigger: "change" },
    node_start_id: [{
        validator: (rule, value) => { if (value === null || value === '') { return new Error('请选择起始站点'); } return true; },
        required: true, trigger: "change"
    }],
    node_to_id: [{
        validator: (rule, value) => { if (value === null || value === '') { return new Error('请选择目标站点'); } return true; },
        required: true, trigger: "change"
    }],
    simulation: [{ required: true, validator: (rule, value) => { if (value === null) return new Error('请选择虚拟设备'); return true; }, trigger: "change" }],
    is_connected: [{ required: true, validator: (rule, value) => { if (value === null) return new Error('请选择是否连接'); return true; }, trigger: "change" }],
    status: [{ required: true, validator: (rule, value) => { if (value === null) return new Error('请选择状态'); return true; }, trigger: "change" }],
    battery: { required: true, type: "number", min: 0, max: 100, message: "电池电量应在0到100之间", trigger: "change" },
    angle: { required: true, type: "number", min: 0, max: 360, message: "角度应在0到360之间", trigger: "change" },
    speed: { required: true, type: "number", min: 0, max: 100, message: "速度应在0到100之间", trigger: "change" },
}

const simulationOptions = [
    { label: "是", value: 1 },
    { label: "否", value: 0 },
];

const isConnectedOptions = [
    { label: "是", value: 1 },
    { label: "否", value: 0 },
];

const statusOptions = [
    { label: "空闲", value: "idle" },
    { label: "运行中", value: "running" },
    { label: "充电中", value: "charging" },
    { label: "维修中", value: "maintenance" },
    { label: "未知", value: "unknown" },
];

const NodeOptions = ref([]);

const get_station_options = async () => {
    try {
        const response = await axios.get(API_URLS.map_node.nameList);
        if (response.data.code === 200) {
            NodeOptions.value = response.data.data.map(item => ({
                label: item[1],
                value: item[0]
            }));
            console.log(NodeOptions.value);
        } else {
            message.error(`获取站点名称列表失败: ${response.data.msg}`);
        }
    } catch (error) {
        message.error("获取站点名称列表失败: " + error.message);
    }
}

onMounted(async () => {
    await get_station_options();
});

const submitForm = async () => {
    await formRef.value.validate();
    loading.value = true;

    if (!formRef.value) return;
    try {
        const response = await axios.post(API_URLS.agv.createsimulation, agvForm.value, { params: {}, });

        if (response.data.code === 200) {
            message.success('添加仿真成功！');
            router.push("/AGV/AGV_simulation_list");
        } else {
            message.error(`添加仿真失败: ${response.data.msg}`);
        }
    } catch (error) {
        message.error('添加仿真出错: ' + error.message);
    } finally {
        loading.value = false;
    }
};

// 取消操作
const handleCancel = () => {
    router.push("/AGV/AGV_simulation_list");
};
</script>

<style scoped>
.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}
</style>
